// src/permission.js
import router from '@/router';
import store from '@/store';
import {getToken} from '@/utils/auth';
import NProgress from 'nprogress'; // 进度条
import 'nprogress/nprogress.css'; // 进度条样式
import {addDynamicRoutes} from '@/router'
import Message from "element-ui/packages/message";
import {getUserMenu} from "@/api/user";
import {treeDataTranslate} from "@/utils/util";
import pages from "@/pages";

NProgress.configure({showSpinner: false}); // 进度条配置

const whiteList = ['/login', '/auth-redirect'];

router.beforeEach(async (to, from, next) => {
  NProgress.start();

  const hasToken = getToken();

  if (hasToken) {
    const hasGetUserInfo = store.getters.staff;
    getUserMenu(hasGetUserInfo.id).then(res => {
      store.commit('user/SET_USERMENU', res.list)
      let treeDataTranslate1 = treeDataTranslate(res.list, 'id', 'pid');
      store.commit('user/SET_TREE_MENU', treeDataTranslate1)

      const route = {
        path: '/',
        component: () => import('@/layout2/index'),
        // redirect: res.list[0].path,
        children: []
      }
      for (let i = 0; i < res.list.length; i++) {
        if (res.list[i].level == 2) {
          // if (!route.redirect) {
          //   route.redirect = res.list[i].url
          // }
          route.children.push({
            path: res.list[i].url,
            meta: {
              title: res.list[i].moniker,
            },
            component: pages[res.list[i].url] //import(`@${res.list[i].url}`),
          })
        }
      }
      res.list.filter(item => {
        if (item.level == 1) {
          if (res.list.filter(item2 => item2.pid == item.id).length == 0) {
            route.children.push({
              path: item.url,
              meta: {
                title: item.moniker,
              },
              component: pages[item.url] //import(`@${item.url}`),
            })
          }
        }

      })
      router.addRoutes([route])

      // router.push({path: '/'})
      next()
    }).catch(() => {
      // this.loading = false
    })
    if (!hasGetUserInfo) {
      try {
        // 获取用户信息
        await store.dispatch('user/getInfo');
        // hack method to ensure addRoutes is complete
        next({...to, replace: true});
      } catch (error) {
        // 移除 token 并重新登录
        await store.dispatch('user/resetToken');
        console.error('Failed to get user info:', error);
        Message.error(error.message || 'Has Error');
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    } else {
      next();
    }
  } else {
    if (to.path === '/login') {
      sessionStorage.clear()
      next()
    } else {
      next('/login')
    }
    NProgress.done();
  }

});

router.afterEach(() => {
  NProgress.done();
});
